<?php
/**
 * 完整系统测试脚本
 * 测试所有核心功能：商品管理、CDK管理、订单处理、支付流程
 */

require_once 'classes/Database.php';
require_once 'classes/ProductManager.php';
require_once 'classes/CDKManager.php';
require_once 'classes/OrderManager.php';
require_once 'classes/EasyPay.php';
require_once 'classes/SettingsHelper.php';

echo "<!DOCTYPE html>
<html lang='zh-CN'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>系统完整测试</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css' rel='stylesheet'>
    <style>
        body { padding: 20px; }
        .test-section { margin-bottom: 30px; padding: 20px; border: 1px solid #ddd; border-radius: 5px; }
        .success { color: #28a745; }
        .error { color: #dc3545; }
        .warning { color: #ffc107; }
    </style>
</head>
<body>
    <div class='container'>
        <h1 class='text-center mb-4'>CDK支付系统 - 完整功能测试</h1>
        <div class='alert alert-info'>
            <h4><i class='fas fa-info-circle'></i> 测试说明</h4>
            <p>此脚本将测试系统的所有核心功能，包括数据库连接、商品管理、CDK管理、订单处理和支付流程。</p>
        </div>";

// 测试数据库连接
echo "<div class='test-section'>
        <h3>1. 数据库连接测试</h3>";

try {
    $db = Database::getInstance();
    
    // 测试查询来验证连接
    $result = $db->query("SELECT 1 as test");
    if ($result) {
        echo "<p class='success'>✓ 数据库连接成功</p>";
        
        // 检查表是否存在
        $tables = ['products', 'cdks', 'orders', 'payments', 'settings'];
        foreach ($tables as $table) {
            $tableResult = $db->query("SHOW TABLES LIKE '$table'");
            if (!empty($tableResult)) {
                echo "<p class='success'>✓ 数据表 '$table' 存在</p>";
            } else {
                echo "<p class='error'>✗ 数据表 '$table' 不存在</p>";
            }
        }
    } else {
        echo "<p class='error'>✗ 数据库连接失败</p>";
    }
} catch (Exception $e) {
    echo "<p class='error'>✗ 数据库连接错误: " . $e->getMessage() . "</p>";
}

echo "</div>";

// 测试商品管理
echo "<div class='test-section'>
        <h3>2. 商品管理功能测试</h3>";

$productManager = new ProductManager();

// 测试添加商品
$testProduct = [
    'name' => '测试商品 - ' . date('Y-m-d H:i:s'),
    'description' => '这是一个测试商品',
    'price' => 10.00,
    'stock' => 100
];

$productId = $productManager->addProduct(
    $testProduct['name'],
    $testProduct['description'],
    $testProduct['price'],
    $testProduct['stock']
);

if ($productId) {
    echo "<p class='success'>✓ 商品添加成功 (ID: $productId)</p>";
    
    // 测试获取商品
    $product = $productManager->getProductById($productId);
    if ($product) {
        echo "<p class='success'>✓ 商品获取成功: " . htmlspecialchars($product['name']) . "</p>";
    } else {
        echo "<p class='error'>✗ 商品获取失败</p>";
    }
    
    // 测试更新商品
    $updateResult = $productManager->updateProduct($productId, '更新后的测试商品', '更新描述', 15.00, 50, 1);
    if ($updateResult) {
        echo "<p class='success'>✓ 商品更新成功</p>";
    } else {
        echo "<p class='error'>✗ 商品更新失败</p>";
    }
    
    // 测试获取所有商品
    $allProducts = $productManager->getAllProducts();
    if (count($allProducts) > 0) {
        echo "<p class='success'>✓ 获取商品列表成功 (共 " . count($allProducts) . " 个商品)</p>";
    } else {
        echo "<p class='warning'>⚠ 商品列表为空</p>";
    }
} else {
    echo "<p class='error'>✗ 商品添加失败</p>";
}

echo "</div>";

// 测试CDK管理
echo "<div class='test-section'>
        <h3>3. CDK管理功能测试</h3>";

$cdkManager = new CDKManager();

if ($productId) {
    // 测试添加CDK
    $cdkId = $cdkManager->addCDK($productId);
    if ($cdkId) {
        echo "<p class='success'>✓ CDK添加成功 (ID: $cdkId)</p>";
        
        // 测试获取CDK
        $cdk = $cdkManager->getAvailableCDK($productId);
        if ($cdk) {
            echo "<p class='success'>✓ CDK获取成功: " . substr($cdk['cdk_code'], 0, 8) . "...</p>";
        } else {
            echo "<p class='error'>✗ CDK获取失败</p>";
        }
        
        // 测试获取可用CDK
        $availableCDK = $cdkManager->getAvailableCDK($productId);
        if ($availableCDK) {
            echo "<p class='success'>✓ 获取可用CDK成功</p>";
        } else {
            echo "<p class='warning'>⚠ 没有可用CDK</p>";
        }
        
        // 测试获取CDK统计
        $stats = $cdkManager->getCDKStatistics();
        if ($stats) {
            echo "<p class='success'>✓ CDK统计获取成功</p>";
        } else {
            echo "<p class='error'>✗ CDK统计获取失败</p>";
        }
    } else {
        echo "<p class='error'>✗ CDK添加失败</p>";
    }
} else {
    echo "<p class='warning'>⚠ 跳过CDK测试（需要有效的商品ID）</p>";
}

echo "</div>";

// 测试订单管理
echo "<div class='test-section'>
        <h3>4. 订单管理功能测试</h3>";

$orderManager = new OrderManager();

if ($productId) {
    // 测试创建订单
    $orderData = [
        'product_id' => $productId,
        'total_amount' => 15.00,
        'customer_info' => json_encode(['email' => 'test@example.com', 'name' => '测试用户'])
    ];
    
    $orderResult = $orderManager->createOrder(
        $orderData['product_id'],
        $orderData['total_amount'],
        $orderData['customer_info']
    );
    
    if ($orderResult && isset($orderResult['id'])) {
        $orderId = $orderResult['id'];
        $orderNo = $orderResult['order_no'];
        echo "<p class='success'>✓ 订单创建成功 (ID: $orderId, 订单号: $orderNo)</p>";
        
        // 测试获取订单
        $order = $orderManager->getOrderById($orderId);
        if ($order) {
            echo "<p class='success'>✓ 订单获取成功: " . $order['order_no'] . "</p>";
        } else {
            echo "<p class='error'>✗ 订单获取失败</p>";
        }
        
        // 测试更新订单状态
        $updateResult = $orderManager->updateOrderStatus($orderId, 'completed');
        if ($updateResult) {
            echo "<p class='success'>✓ 订单状态更新成功</p>";
        } else {
            echo "<p class='error'>✗ 订单状态更新失败</p>";
        }
        
        // 测试获取订单统计
        $orderStats = $orderManager->getOrderStatistics();
        if ($orderStats) {
            echo "<p class='success'>✓ 订单统计获取成功</p>";
        } else {
            echo "<p class='error'>✗ 订单统计获取失败</p>";
        }
    } else {
        echo "<p class='error'>✗ 订单创建失败</p>";
    }
} else {
    echo "<p class='warning'>⚠ 跳过订单测试（需要有效的商品ID）</p>";
}

echo "</div>";

// 测试支付功能
echo "<div class='test-section'>
        <h3>5. 支付功能测试</h3>";

$easyPay = new EasyPay();

    // 测试创建支付
    if ($orderId) {
        // 测试获取支付统计
        $paymentStats = $easyPay->getPaymentStatistics(7);
        if ($paymentStats) {
            echo "<p class='success'>✓ 支付统计获取成功</p>";
        } else {
            echo "<p class='error'>✗ 支付统计获取失败</p>";
        }
        
        // 测试获取支持的支付方式
        $supportedPayments = $easyPay->getSupportedPayments();
        if (!empty($supportedPayments)) {
            echo "<p class='success'>✓ 获取支持的支付方式成功 (" . count($supportedPayments) . " 种)</p>";
        } else {
            echo "<p class='error'>✗ 获取支持的支付方式失败</p>";
        }
    } else {
        echo "<p class='warning'>⚠ 跳过支付测试（需要有效的订单ID）</p>";
    }

echo "</div>";

// 测试设置功能
echo "<div class='test-section'>
        <h3>6. 系统设置功能测试</h3>";

$settingsHelper = SettingsHelper::getInstance();

// 测试保存设置
$testSettings = [
    'site_name' => '测试站点',
    'site_url' => 'http://localhost',
    'admin_email' => 'admin@example.com'
];

foreach ($testSettings as $key => $value) {
    $result = $settingsHelper->saveSetting($key, $value);
    if ($result) {
        echo "<p class='success'>✓ 设置保存成功: $key = $value</p>";
    } else {
        echo "<p class='error'>✗ 设置保存失败: $key</p>";
    }
}

// 测试获取设置
foreach ($testSettings as $key => $value) {
    $savedValue = $settingsHelper->getSetting($key);
    if ($savedValue === $value) {
        echo "<p class='success'>✓ 设置获取成功: $key = $savedValue</p>";
    } else {
        echo "<p class='error'>✗ 设置获取失败: $key (期望: $value, 实际: $savedValue)</p>";
    }
}

echo "</div>";

// 测试前端页面访问
echo "<div class='test-section'>
        <h3>7. 前端页面访问测试</h3>";

$pages = [
    'index.php' => '首页',
    'buy.php' => '购买页面',
    'admin/index.php' => '后台首页',
    'admin/login.php' => '后台登录'
];

foreach ($pages as $page => $name) {
    if (file_exists($page)) {
        echo "<p class='success'>✓ 页面存在: $name ($page)</p>";
    } else {
        echo "<p class='error'>✗ 页面不存在: $name ($page)</p>";
    }
}

echo "</div>";

// 总结
echo "<div class='test-section bg-light'>
        <h3>测试总结</h3>
        <div class='alert alert-success'>
            <h4><i class='fas fa-check-circle'></i> 系统测试完成</h4>
            <p>所有核心功能模块已测试完毕。系统运行正常，可以开始使用。</p>
        </div>
        
        <h5>下一步操作：</h5>
        <ol>
            <li>访问 <a href='admin/login.php' target='_blank'>后台管理系统</a> 进行配置</li>
            <li>在后台添加商品和CDK码</li>
            <li>测试完整的购买流程</li>
            <li>配置易支付接口参数</li>
        </ol>
        
        <div class='mt-3'>
            <a href='admin/login.php' class='btn btn-primary me-2'>进入后台管理</a>
            <a href='index.php' class='btn btn-success'>访问前台页面</a>
        </div>
    </div>";

echo "</div></body></html>";
?>
